from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from rest_framework.generics import ListAPIView
from flower import models,flowerser
from django.db.models import Q
#参数名称 /flower/list/ 参数  page 页码  size  name 查询名称  maxprice minprice 范围 color 用途  purpose

class FlowerPage(PageNumberPagination):
  page_size = 2
  page_size_query_param = 'size'
  page_query_param = 'page'

class Purpose(APIView):
  def get(self,request):
      purpose=models.Purpose.objects.all()
      ser=flowerser.PurposeSerializer(purpose,many=True)
      return Response({"msg":"ok","data":ser.data})

# Create your views here.
class FlowerList(ListAPIView):
  queryset = models.Flower.objects.all()
  serializer_class = flowerser.FlowerSerializer
  pagination_class = FlowerPage
  def get_queryset(self):
      query=Q()
      name=self.request.query_params.get('name')
      color=self.request.query_params.get('color')
      purpose=self.request.query_params.get('purpose')
      minprice=self.request.query_params.get('min')
      maxprice=self.request.query_params.get('max')
      if name:
          query &= Q(name__contains=name)
      if color:
          query &= Q(color=color)
      if purpose:
          query &= Q(purpose=purpose)
      if minprice and maxprice:
          query &= Q(price__range=(minprice,maxprice))
      if minprice:
          query &= Q(price__gte=minprice)
      if maxprice:
          query &= Q(price__lte=maxprice)
      return self.queryset.filter(query)


#添加商品到购物车
class AddFlower(APIView):
  def post(self,request):
      flower=request.data.get("flower")
      user=request.data.get("user")
      #判断当前用户是否购买过次商品  如果买过 数量加一 如果没有买过执行新增一个记录
      info=models.MyCart.objects.filter(user=user,flower=flower).first()
      if info:
          info.number+=1
          info.save()
          return Response({"msg":"添加成功"})
      else:
          ser=flowerser.FlowerCartSerializer(data=request.data)
          if ser.is_valid():
              ser.save()
              return Response({"msg":"添加成功"})
          else:
              return Response({"msg":ser.errors})

#购物车列表
class CartList(APIView):
    def get(self,request):
        user=request.query_params.get("user")
        cart=models.MyCart.objects.filter(user=user)
        ser=flowerser.MyCartSerializer(cart,many=True)
        return Response({"msg":"ok","data":ser.data})


#修改数量
class CartUpdate(APIView):
    #购物车主键 id  新的数量  number
    def put(self,request):
        id=request.data.get("id")
        number=request.data.get("number")
        info=models.MyCart.objects.filter(id=id).first()
        info.number=number
        info.save()
        return Response({"msg":"修改成功"})

#修改状态
class CartSelect(APIView):
    #购物车主键 id  新的数量  number
    def put(self,request):
        id=request.data.get("id")
        info=models.MyCart.objects.filter(id=id).first()
        info.select=not info.select
        info.save()
        return Response({"msg":"修改成功"})

class CartMany(APIView):
    def delete(self,request):
        user=request.query_params.get("user")
        models.MyCart.objects.filter(user=user,select=True).delete()
        return Response({"msg":"删除成功"})
import time
from utils.Alipay import AliPaySDK
class OrderView(APIView):
    def post(self,request):
        #生成订单  返回支付的链接
        #拿到购物车选中的商品
        user=request.data.get("user")
        carts=models.MyCart.objects.filter(user=user,select=True)
        total=0
        for cart in carts:
            total+=cart.number*cart.flower.price
        orderdata={
            "user":user,
            "total":total,
            "orderno":str(time.strftime("%Y%m%d%H%M%S",time.localtime()))
        }
        orderser=flowerser.MyOrderSerializer(data=orderdata)
        if orderser.is_valid():
            orderser.save()
            #订单详情
            for cart in carts:
                detail={
                    "order":orderser.data.get("id"),
                    "flower":cart.flower.id,
                    "number":cart.number,
                    "price":cart.flower.price,
                    "img":'http://127.0.0.1:8000/uploads/'+str(cart.flower.img)
                }
                detailser=flowerser.MyDetailSerializer(data=detail)
                if detailser.is_valid():
                    detailser.save()
                    #删除购物车中数据
                    cart.delete()
        ali=AliPaySDK()
        #ali.page_pay(orderdata.orderno,orderdata.total,"鲜花付款")
        return  Response(ali.page_pay(orderdata.get("orderno"),orderdata.get("total"),"鲜花付款"))
